package com.example.black.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 加入padding 隐藏的线就又出现了，猜测由于不是从 draw层面解决的，只是通过 {@see #getItemOffsets}
 * 将边界进行了偏移藏起来，但其实并没有消失，通过add的方式偏移的视图又会回来
 */
public class MyItemDecoration extends RecyclerView.ItemDecoration {
    public static final int HORIZONTAL = LinearLayout.HORIZONTAL;
    public static final int VERTICAL= LinearLayout.VERTICAL;
    public static final int GRID = 2;
    private static final String TAG = MyItemDecoration.class.getSimpleName();
    private int[] ATTRS = new int[]{android.R.attr.listDivider};
    private int orientation;
    private Drawable mDivider;
    public MyItemDecoration(Context context,int orientation) {
        final TypedArray typedArray = context.obtainStyledAttributes(ATTRS);
        mDivider = typedArray.getDrawable(0);
        this.orientation = orientation;
        if (mDivider == null){
            throw new UnsupportedOperationException("divider must not null ");
        }
        typedArray.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        //绘制分割线
        if (parent.getParent() == null || mDivider == null){
            return;
        }
        if (orientation == VERTICAL){
            drawVertical(c,parent);
        } else if (orientation == HORIZONTAL){
            drawHorizontal(c,parent);
        }else {
            drawVertical(c,parent);
            drawHorizontal(c,parent);
        }

    }

    private void drawHorizontal(Canvas c, RecyclerView parent) {
        c.save();

//        final int top;
//        final int bottom;
//        //noinspection AndroidLintNewApi - NewApi lint fails to handle overrides.
//        if (parent.getClipToPadding()) {
//            top = parent.getPaddingTop();
//            bottom = parent.getHeight() - parent.getPaddingBottom();
//            canvas.clipRect(parent.getPaddingLeft(), top,
//                    parent.getWidth() - parent.getPaddingRight(), bottom);
//        } else {
//            top = 0;
//            bottom = parent.getHeight();
//        }
//
//        final int childCount = parent.getChildCount();
//        for (int i = 0; i < childCount; i++) {
//            final View child = parent.getChildAt(i);
//            parent.getLayoutManager().getDecoratedBoundsWithMargins(child, mBounds);
//            final int right = mBounds.right + Math.round(child.getTranslationX());
//            final int left = right - mDivider.getIntrinsicWidth();
//            mDivider.setBounds(left, top, right, bottom);
//            mDivider.draw(canvas);
//        }

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int left = child.getRight() + params.rightMargin;
            int right = left + mDivider.getIntrinsicWidth();
            int top = child.getTop() - params.topMargin;
            int bottom = child.getBottom() + params.bottomMargin;

            mDivider.setBounds(left,top,right,bottom);
            mDivider.draw(c);
        }

        c.restore();
    }

    private void drawVertical(Canvas c, RecyclerView parent) {
        c.save();

//        final int left;
//        final int right;
//        //noinspection AndroidLintNewApi - NewApi lint fails to handle overrides.
//        if (parent.getClipToPadding()) {
//            left = parent.getPaddingLeft();
//            right = parent.getWidth() - parent.getPaddingRight();
//            canvas.clipRect(left, parent.getPaddingTop(), right,
//                    parent.getHeight() - parent.getPaddingBottom());
//        } else {
//            left = 0;
//            right = parent.getWidth();
//        }
//
//        final int childCount = parent.getChildCount();
//        for (int i = 0; i < childCount; i++) {
//            final View child = parent.getChildAt(i);
//            parent.getDecoratedBoundsWithMargins(child, mBounds);
//            final int bottom = mBounds.bottom + Math.round(child.getTranslationY());
//            final int top = bottom - mDivider.getIntrinsicHeight();
//            mDivider.setBounds(left, top, right, bottom);
//            mDivider.draw(canvas);
//        }


        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int left = child.getLeft() - params.leftMargin;
            int right = child.getRight()+ params.rightMargin;
            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
        c.restore();

    }

    /**
     *
     * 设置为0发生了什么？作用？
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        //获取条目间距
        if (mDivider == null){
            outRect.set(0,0,0,0);
            return;
        }
        if (orientation == VERTICAL){
            outRect.set(0,0,0,mDivider.getIntrinsicHeight());
        }else if (orientation == HORIZONTAL){
            outRect.set(0,0,mDivider.getIntrinsicWidth(),0);
        }else {
            outRect.set(0,0,mDivider.getIntrinsicWidth(),mDivider.getIntrinsicHeight());
            if(isLastColumn(parent,view)){
                outRect.right = 0;
            }
            if(isLastRow(parent,view)){
                Log.e(TAG, "ssss---->getItemOffsets: isLastRow "+parent.getChildLayoutPosition(view) );
                outRect.bottom = 0;
                outRect.set(0,0,0,0);
            }
        }
    }

    private boolean isLastRow(RecyclerView recyclerView,View childView) {
       int itemCount = recyclerView.getAdapter().getItemCount();
       int position = ((RecyclerView.LayoutParams) childView.getLayoutParams()).getViewLayoutPosition()+1;
        int spanCount =( (GridLayoutManager)recyclerView.getLayoutManager()).getSpanCount();
        int totalRows = (itemCount /spanCount) + (itemCount % spanCount == 0 ? 0 : 1 );
        int currentRow =  (position /spanCount) + (position % spanCount == 0 ? 0 : 1 );
        Log.e(TAG, "getItemOffsets: totalRows "+totalRows + "currentRow "+ currentRow);
        return totalRows ==  currentRow;
    }

    /**
     *
     * @return 视频教授的算法
     */
//    private boolean isLastRow(RecyclerView recyclerView,View childView) {
//        int itemCount = recyclerView.getAdapter().getItemCount();
//        int spanCount = ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanCount();
//        int lastRowCount = itemCount % spanCount;
//        Log.e(TAG, "getItemOffsets:---------> itemCount "+itemCount + "spanCount "+ spanCount+" lastRowCount "+ lastRowCount);
//        return lastRowCount == 0 || lastRowCount < spanCount;
//    }

    private boolean isLastColumn(RecyclerView recyclerView ,View childView) {
        int position = recyclerView.getChildLayoutPosition(childView) + 1;
        int spanCount =( (GridLayoutManager)recyclerView.getLayoutManager()).getSpanCount();
        return (position  % spanCount) == 0;
    }


}
